package com.vmove.childtrain.protocol;


import com.vmove.childtrain.common.Constants;
import com.vmove.childtrain.utils.ByteUtil;

/**
 * Created by Administrator on 2018/1/18.
 * @Description:协议基类
 */
public abstract class AbsProtocol {
    protected byte head=(byte) 0xA5;
    protected byte len=0;//长度 = data.len+8
    protected byte[] pad= ByteUtil.getBytes1(Constants.PADID);//pad码 2个byte 低位在前
    protected byte light;//light地址
    protected byte dataType;
    protected byte[] data;
    protected byte check=0x00;//校验码
    protected byte end= (byte) 0x5A;//停止位

    public byte getHead() {
        return head;
    }

    public void setHead(byte head) {
        this.head = head;
    }

    public byte getLen() {
        return len;
    }

    public void setLen(byte len) {
        this.len = len;
    }

    public byte getDataType() {
        return dataType;
    }

    protected void setDataType(byte dataType) {
        this.dataType = dataType;
    }

    public byte[] getData() {
        return data;
    }

    public AbsProtocol setData(byte[] data) {
        this.data = data;
        return this;
    }

    public byte getCheck() {
        return check;
    }

    public void setCheck(byte check) {
        this.check = check;
    }

    public byte getEnd() {
        return end;
    }

    public void setEnd(byte end) {
        this.end = end;
    }

    public byte[] getPad() {
        return pad;
    }

    public void setPad(byte[] pad) {
        this.pad = pad;
    }

    public void setPad(short pad) {
        this.pad = ByteUtil.getBytes1(pad);
    }

    public byte getLight() {
        return light;
    }

    public void setLight(byte light) {
        this.light = light;
    }

    public AbsProtocol setLight(int light) {
        this.light = ByteUtil.getBytes1(light)[0];
        return this;
    }

    /**
     * 组包
     */
    public byte[] getBytes(){
        len = ByteUtil.getBytes(data.length +8)[3];
        byte[] result = new byte[len];
        result[0] = head;
        result[1] = len;
        result[2] = pad[0];
        result[3] = pad[1];
        result[4] = light;
        result[5] = dataType;
        for (int i=6;i<len-2;i++){
            result[i] = data[i-6];
        }
        result[len-2] = check;
        result[len-1] = end;
        return result;
    }

    public int getDataLen(){
        if (data!=null){
            return data.length;
        }
        return 0;
    }
}
